﻿package graphics.raster 
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	/**
	 * ...
	 * @author Nicolas Barradeau
	 */
	public class ComponentLabelling
	{
		static private var bd:BitmapData;
		
		public function ComponentLabelling(){}
		
		static public function process( source:BitmapData ):Vector.<Bitmap>
		{
			
			var bitmaps:Vector.<Bitmap> = new Vector.<Bitmap>();
			
			bd = source.clone();
			bd.threshold( source, source.rect, new Point(), '>', 0x00000000, 0xFFFFFFFF );
			
			var tmp:BitmapData = bd.clone();
			var p:Point = new Point();
			
			var w:int = bd.width, h:int = bd.height, i:int = 0, max:int = w * h, _x:int, _y:int, _c:uint;
			
			while ( i++ < max )
			{
				
				_x = i % w;
				_y = int( i / w );
				_c = bd.getPixel32( _x, _y );
				if ( _c != 0 && _c != 0xFFFF0000 )
				{
					_c = 0xFFFF0000;
					bd.floodFill( _x, _y, _c );
					
					tmp.fillRect( tmp.rect, 0 );
					tmp.threshold( bd, tmp.rect, p, '==', _c, 0xFFFFFFFF );
					
					var rect:Rectangle = tmp.getColorBoundsRect( _c, 0, false );
					var element:Bitmap = new Bitmap( new BitmapData( rect.width, rect.height, true, 0 ) );
					element.bitmapData.copyPixels( tmp, rect, p );
					element.x = rect.x;
					element.y = rect.y;
					bitmaps.push( element );
					
					
					
					bd.floodFill( _x, _y, 0 );
					
				}
			}
			
			return bitmaps;
			
		}
	}

}